import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) { // 防止重复点击侧边栏异常
  return originalPush.call(this, location).catch(err => err)
}
const routes = [
  {
    path: '/login',
    name: 'login',
    component: () => import('@/System/newLogin.vue')
  },

  {
    path: '/admin',
    name: 'index',
    component: () => import('@/System/MyIndex.vue'),
    redirect: '/user',
    children: [
      {
        path: '/user',
        name: 'user',
        component: () => import('@/views/admin/userView.vue')
      },
      {
        path: '/dish',
        name: 'dish',
        component: () => import('@/views/admin/userDishView.vue')
      },
      {
        path: '/category',
        name: 'category',
        component: () => import('@/views/admin/categoryView.vue')
      }
      // {
      //   path: '/weather',
      //   name: 'weather',
      //   component: () => import('@/views/admin/Weather.vue')
      // }
    ]
  }, {
    path: '/My_user',
    name: 'My_user',
    component: () => import('@/System/MyIndex.vue'),
    redirect: '/userInfo',
    children: [
      {
        path: '/userInfo',
        name: 'userInfo',
        component: () => import('@/views/user/userInfoView.vue')
      },
      {
        path: '/userDish',
        name: 'userDish',
        component: () => import('@/views/user/dishView.vue')
      },
      {
        path: '/shopCart',
        name: 'shopCart',
        component: () => import('@/views/user/shoppingCart.vue')
      },
      {
        path: '/order',
        name: 'order',
        component: () => import('@/views/user/orderView.vue')
      }
    ]
  }

]
const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  // to：将要访问的路径
  // from：代表从哪个路径跳转而来
  // next：是一个函数代表放行
  // next() 放行  next('/login') 强制跳转
  if (to.path === '/login') {
    return next()
  } else {
    // 获取token
    const tokenStr = window.sessionStorage.getItem('token')
    if (!tokenStr) {
      return next('/login')
    } else {
      next()
    }
  }
})
export default router
